package com.c.ctgproject.ui.archives.shoot

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.database.Cursor
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import com.c.ctgproject.R
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.customview.GlideImageLoader
import com.c.ctgproject.customview.ImagePickerLoader
import com.c.ctgproject.utils.MyLog
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.imagepicker.data.ImagePickType
import com.lwkandroid.widget.ninegridview.NineGirdImageContainer
import com.lwkandroid.widget.ninegridview.NineGridBean
import com.lwkandroid.widget.ninegridview.NineGridView
import com.nanchen.compresshelper.CompressHelper
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.activity_shoot_photo_video.*
import java.io.File


/**
 *作者:LiBW
 *创建日期: 2020/9/2
 *描述: 档案部拍摄照片和视频页面
 */
class ShootPhotoVideoActivity : BaseActivity() {

    private val requestCodePicker = 1001
    //视频选择器请求码
    private val requestCodeChoose = 1002

    private val files: ArrayList<File> = ArrayList()
    private val files2: ArrayList<File> = ArrayList()


    override fun getLayout() = R.layout.activity_shoot_photo_video

    override fun event() {
        //设置图片加载器，这个是必须的，不然图片无法显示
        ninegridview.setImageLoader(GlideImageLoader())
        //设置显示列数，默认3列
        ninegridview.setColumnCount(3)
        //设置是否为编辑模式，默认为false
        ninegridview.setIsEditMode(true)
        //设置单张图片显示时的尺寸，默认100dp
        ninegridview.setSingleImageSize(150)
        //设置单张图片显示时的宽高比，默认1.0f
        ninegridview.setSingleImageRatio(0.8f)
        //设置最大显示数量，默认9张
        ninegridview.setMaxNum(5)
        //设置图片显示间隔大小，默认3dp
        ninegridview.setSpcaeSize(4)
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        ninegridview.setRatioOfDeleteIcon(0.15f)
        //设置“+”号的图片
        ninegridview.setIcAddMoreResId(R.drawable.ic_ngv_add_pic)
        //设置各类点击监听
        ninegridview.setOnItemClickListener(object : NineGridView.onItemClickListener {
            override fun onNineGirdItemDeleted(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {
                if (files.isEmpty()) {
                    files.removeAt(position)
                }
            }

            override fun onNineGirdItemClick(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {

            }

            override fun onNineGirdAddMoreClick(cha: Int) {
                //编辑模式下，图片展示数量尚未达到最大数量时，会显示一个“+”号，点击后回调这里
                val imageLoader = ImagePicker()
                    .cachePath(Environment.getExternalStorageDirectory().absolutePath)
                    .pickType(ImagePickType.MULTI)
                    .displayer(ImagePickerLoader())
                    .maxNum(cha)
                    .start(this@ShootPhotoVideoActivity, requestCodePicker)
            }

        })


        //设置图片加载器，这个是必须的，不然图片无法显示
        mVideoShow1.setImageLoader(GlideImageLoader())
        //设置显示列数，默认3列
        mVideoShow1.setColumnCount(3)
        //设置是否为编辑模式，默认为false
        mVideoShow1.setIsEditMode(true)
        //设置单张图片显示时的尺寸，默认100dp
        mVideoShow1.setSingleImageSize(150)
        //设置单张图片显示时的宽高比，默认1.0f
        mVideoShow1.setSingleImageRatio(0.8f)
        //设置最大显示数量，默认9张
        mVideoShow1.setMaxNum(5)
        //设置图片显示间隔大小，默认3dp
        mVideoShow1.setSpcaeSize(4)
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        mVideoShow1.setRatioOfDeleteIcon(0.15f)
        //设置“+”号的图片
        mVideoShow1.setIcAddMoreResId(R.drawable.icon_add_video)
        //设置各类点击监听
        mVideoShow1.setOnItemClickListener(object : NineGridView.onItemClickListener {
            override fun onNineGirdItemDeleted(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {
                if (files2.isEmpty()) {
                    files2.removeAt(position)
                }
            }

            override fun onNineGirdItemClick(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {

            }

            override fun onNineGirdAddMoreClick(cha: Int) {
               //编辑模式下，图片展示数量尚未达到最大数量时，会显示一个“+”号，点击后回调这里
                getVideo()
            }

        })


    }

    override fun click() {
        mShootPhotoBTN.setOnClickListener {
            getVideo()
        }
    }

    private fun getVideo() {
        //视频选择器
        Matisse.from(this)
            .choose(MimeType.ofVideo())
            //是否只显示选择的类型的缩略图，就不会把所有图片视频都放在一起，而是需要什么展示什么
            .showSingleMediaType(true)
            //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
            .capture(true)
            .captureStrategy(CaptureStrategy(true, "com.ctgoe.paoding.gq.fileProvider"))
            //有序选择图片 123456...
            .countable(true)
            //最大选择数量为9
            .maxSelectable(9)
            //选择方向
            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            //界面中缩略图的质量
            .thumbnailScale(0.8f)
            //蓝色主题
            .theme(R.style.Matisse_Zhihu)
            //黑色主题
            .theme(R.style.Matisse_Dracula)
            //Glide加载方式
            .imageEngine(GlideEngine())
            //请求码
            .forResult(requestCodeChoose)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == requestCodePicker && resultCode == Activity.RESULT_OK && data != null) {

            val list: List<ImageBean> =data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
            val resultList: MutableList<NineGridBean> = java.util.ArrayList()
            for (imageBean in list) {
                val nineGirdData = NineGridBean(imageBean.imagePath)
                val file = File(imageBean.imagePath)
                val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
                files.add(newFile)
                resultList.add(nineGirdData)
            }
            ninegridview.addDataList(resultList)
        }

        if (requestCode == requestCodeChoose && resultCode == Activity.RESULT_OK && data != null) {
            //图片路径 同样视频地址也是这个 根据requestCode
            val mSelected = Matisse.obtainResult(data)
            val resultList: MutableList<NineGridBean> = java.util.ArrayList()
            MyLog.d("视频地址:$mSelected")

            mSelected.forEach {
                val file = uri2File(it)
                files2.add(file)
                val nineGirdData = NineGridBean(getRealFilePath(this, it))
                resultList.add(nineGirdData)
            }
            mVideoShow1.addDataList(resultList)
        }
    }

    private fun uri2File(uri: Uri): File {
        //uri转换成file
        val arr = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = managedQuery(uri, arr, null, null, null)
        val imgIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor.moveToFirst()
        val imgPath = cursor.getString(imgIndex)
        return File(imgPath)
    }


    @SuppressLint("Recycle")
    private fun getRealFilePath(context: Context, uri: Uri?): String? {
        if (null == uri) return null
        val scheme = uri.scheme
        var data: String? = null
        when {
            scheme == null -> data = uri.path
            ContentResolver.SCHEME_FILE == scheme -> {
                data = uri.path
            }
            ContentResolver.SCHEME_CONTENT == scheme -> {
                val cursor: Cursor = context.contentResolver.query(uri, arrayOf<String>(MediaStore.Images.ImageColumns.DATA), null, null, null)!!
                if (cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }
}